<template>
  <div class="finder">
    <div class="options">
      <t-button @click="onOpenCategoryTools({})">添加一个</t-button>
      <div class="options-right">
        <div class="options__item">
          <span>启用发现</span>
          <t-switch v-model="formData.finderStatus" size="large" :default-value="true">
            <template #label="slotProps">{{ slotProps.value ? $t('switchOpen') : $t('switchClose') }}</template>
          </t-switch>
        </div>
      </div>
    </div>
    <div v-if="formData.ruleFinder.length > 0" class="list">
      <div v-for="finder in formData.ruleFinder" :key="finder.uuid" class="item">
        <div class="item-header">
          <div class="item-header__title">
            <span>{{ finder.name }}</span>
          </div>
          <div class="item-header__option">
            <t-button size="small" theme="success" @click="onOpenCategoryTools(finder)">编辑</t-button>
            <t-popconfirm content="确认删除吗" @confirm="onCategoryItemOption('delete', finder)">
              <t-button size="small" theme="danger">删除</t-button>
            </t-popconfirm>
          </div>
        </div>
        <div v-if="!isObjectEmpty(finder.list)" class="item-cate">
          <div v-for="(val, k) in finder.list" :key="k" class="item-cate-item">
            <div class="item-cate-item__label">
              <t-tag max-width="60" size="small">{{ val.name }}</t-tag>
            </div>
            <div v-if="val.list" class="item-cate-item__list">
              <t-link
                v-for="(value, key) in JSON.parse(val.list)"
                :key="key"
                theme="primary"
                size="small"
                :underline="getIsSelect(finder.uuid, val.type, value)"
                @click="onSelect(finder.uuid, val.type, value)"
              >
                {{ value.name }}
              </t-link>
            </div>
          </div>
        </div>
        <div class="item-preview">{{ getStructureUrl(finder) }}</div>
      </div>
    </div>
    <div v-else class="empty">
      <t-alert message="没找到发现信息，赶快去添加一个吧！" />
    </div>
    <steve-category-tools
      v-model:visible="categoryToolsVisible"
      v-model:value="categoryToolsValue"
      @confirm="onCategoryToolsConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, toRefs, watch } from 'vue';

import SteveCategoryTools from '@/components/steveCategoryTools/index.vue';
import { isObjectEmpty, steveDeepCopy } from '@/utils/common';

const props = defineProps({
  // fromData
  formData: Object,
});

const { formData } = toRefs(props);
const selectObject = ref({});
watch(
  formData,
  (value) => {
    if (!isObjectEmpty(value.ruleFinder)) {
      for (const finder of value.ruleFinder) {
        if (!isObjectEmpty(finder.list)) {
          const obj = {
            steveStructure: '',
            // 翻页序号
            pageIndex: {
              name: '翻页序号',
              value: '1',
            },
          };
          for (const item of finder.list) {
            if (!isObjectEmpty(item.list)) {
              const arr = JSON.parse(item.list);
              // eslint-disable-next-line prefer-destructuring
              obj[`_${item.type}`] = arr[0];
            }
          }
          obj.steveStructure = finder.structure;
          selectObject.value = { ...selectObject.value, [finder.uuid]: obj };
        }
      }
    }
  },
  { deep: true },
);

watch(
  selectObject,
  (value) => {
    for (const key in value) {
      value[key].url = replacePlaceholders(value[key].steveStructure, value[key]);
    }
  },
  { deep: true },
);

// 打开分类工具
const categoryToolsVisible = ref(false);
const categoryToolsValue = ref({});
const onOpenCategoryTools = (item: any) => {
  categoryToolsValue.value = steveDeepCopy(item);
  categoryToolsVisible.value = true;
};

// 分类工具确认事件
const onCategoryToolsConfirm = (v: any) => {
  const finder = formData.value.ruleFinder;
  let bool = false;
  const cate = steveDeepCopy(finder);
  for (let i = 0; i < finder.length; i++) {
    if (finder[i].uuid === v.uuid) {
      cate[i] = v;
      bool = true;
    }
  }
  if (!bool) {
    cate.push(v);
  }
  formData.value.ruleFinder = cate;
  categoryToolsVisible.value = false;
};

// 操作分类
const onCategoryItemOption = (type: string, value: object) => {
  if (type === 'delete') {
    const finderList = formData.value.ruleFinder;
    const cate = [];
    if (!isObjectEmpty(finderList)) {
      for (const finder of finderList) {
        if (finder.uuid !== value.uuid) {
          cate.push(finder);
        }
      }
      formData.value.ruleFinder = cate;
    }
  }
};

// 构造选择
const onSelect = (uuid: string, type: string, value: object) => {
  selectObject.value[uuid][`_${type}`] = value;
};

const getIsSelect = (uuid: string, type: string, value: object) => {
  if (!selectObject.value[uuid]) {
    return false;
  }
  return selectObject.value[uuid][`_${type}`].value === value.value;
};

// 获取构造后的地址
const getStructureUrl = (v: object) => {
  if (!selectObject.value[v.uuid]) {
    return v.structure;
  }
  return selectObject.value[v.uuid].url;
};

interface ReplaceObject {
  [key: string]: { name: string; value: string };
}

function replacePlaceholders(template: string, replaceObject: ReplaceObject): string {
  // 匹配 @{} 格式的正则表达式
  const regex = /@\{([^}]+)\}/g;

  // 使用 replace 方法进行替换
  return template.replace(regex, (match, placeholder) => {
    // placeholder 是 @{} 中的内容，例如 "_cate"、"_rank"、"_size"
    const trimmedPlaceholder = placeholder.trim(); // 去除可能的空格

    // 根据 placeholder 找到对应的值
    if (replaceObject[trimmedPlaceholder]) {
      const { value } = replaceObject[trimmedPlaceholder];
      return value;
    }
    // 如果找不到对应的值，保留原始占位符
    return match;
  });
}
</script>

<style lang="less" scoped>
.finder {
  position: relative;

  .options {
    position: sticky;
    z-index: 1;
    bottom: 0;
    top: 0;
    padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-l);
    background: var(--td-bg-color-container);
    border-bottom: 1px solid var(--td-component-stroke);
    display: flex;
    justify-content: space-between;

    &__item {
      font-size: var(--td-font-size-body-small);
      display: flex;
      align-items: center;

      span {
        margin-right: var(--td-comp-margin-s);
      }
    }
  }

  .empty {
    padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-l);
  }

  .list {
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-l);

    .item {
      position: relative;
      border: 1px solid var(--td-component-stroke);
      border-radius: var(--td-radius-large);
      margin-bottom: var(--td-comp-margin-l);

      &-header {
        display: flex;
        justify-content: space-between;

        &__title {
          span {
            background: var(--td-brand-color);
            padding: var(--td-comp-paddingLR-xs);
            font-size: 12px;
            color: var(--td-text-color-anti);
            border-radius: var(--td-radius-large) 0;
            margin-top: -1px;
            margin-left: -1px;
          }
        }

        &__option {
          padding: var(--td-comp-paddingLR-xs);
        }
      }

      &-cate {
        padding: var(--td-comp-paddingTB-s) 0;

        &-item {
          padding: 0 var(--td-comp-paddingLR-l) var(--td-comp-paddingTB-s);
          display: flex;

          &__label {
            width: 60px;
            font-size: 12px;
            margin-right: var(--td-comp-margin-s);
          }

          &__list {
            flex: 1;

            :deep(.t-link) {
              margin: 0 var(--td-comp-paddingLR-s);
            }
          }
        }
      }

      &-preview {
        border-top: 1px solid var(--td-component-stroke);
        padding: var(--td-comp-paddingTB-s) var(--td-comp-paddingLR-l);
        font-size: 12px;
        word-break: break-all;
      }
    }
  }
}
</style>
